package com.example.forum.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {



    @Resource
    private Count count;

    @Resource
    private RedisListUtil redisListUtil;

    @Resource
    private IArticleService articleService;

    @Resource
    private IUserService UserService;


    private LineCaptcha lineCaptcha;
    /**
     * 生成验证码
     * @param response
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletResponse response) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        // 定义图片的显示大小
        lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 打印日志
            log.info("生成的验证码:{}", lineCaptcha.getCode());
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //System.out.println(Count.FW_Count());
        int c = count.FW_Count();
        log.info("共计访问次数: "+ c);
    }

    /**
     * 用户注册
     *
     * @param username       用户名
     * @param nickname       昵称
     * @param password       密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        /*if(StringUtil.isEmpty(username)
                || StringUtil.isEmpty(nickname)
                || StringUtil.isEmpty(password)
                || StringUtil.isEmpty(passwordRepeat)) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/
        //校验两个密码必须相同
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        // 1. 生成盐
        String salt = UUIDUtil.UUID_32();
        // 2. 生成密码的密文
        String encryptPassword = MD5util.md5Salt(password, salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //调用service层
        UserService.createNormalUser(user);
        return AppResult.success();
    }


    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password, HttpServletRequest request,
                           @ApiParam("验证码") @RequestParam("captcha") @NonNull String captcha) {
        // 1 调用service中的login处理逻辑 返回user对象
        User user = UserService.login(username, password);

        //判断验证码是否正确
        if(!captcha.equals(lineCaptcha.getCode())) {
            log.warn(ResultCode.FAILED_LOGIN_.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN_);
        }
        // 2 如果登录成功,把user对象设置在session对象中
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);

        // 3 返回结果
        int i = count.LoginCount();
        log.info("用户登录成功次数为:" + i);
        return AppResult.success();
    }


    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserinfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {
        //定义返回user对象
        User user = null;
        //根据id值判断user对象获取方式
        if (id == null) {
            //1. 如果id为空,则说明查询的是当前用户信息  从session中取
            HttpSession session = request.getSession(false);
            //从当前session中取出用户对象
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
            Long userId = user.getId();
            user = UserService.SelectById(userId);
        } else {
            //id不为空,查询的是指定id的用户
            user = UserService.SelectById(id);
        }
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //返回结果
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //获取session对象
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("退出成功");
            //表示用户在登录状态
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }


    /**
     * @param username 用户名
     * @param nickname 昵称
     * @param gender   性别
     * @param email    邮箱
     * @param phoneNum 电话号码
     * @param remark   个人简介
     * @return
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username", required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        //1 接收参数
        //2 对参数做非空校验
        if (StringUtil.isEmpty(username)
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark)
                && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }
        //从session中获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //3 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); //用户id
        updateUser.setUsername(username);  //用户名
        updateUser.setNickname(nickname);  // 昵称
        updateUser.setGender(gender);  //性别
        updateUser.setEmail(email);  //邮箱
        updateUser.setPhoneNum(phoneNum); // 电话号码
        updateUser.setRemark(remark);  //个人简介
        //4 调用service中方法
        UserService.modifyInfo(updateUser);
        // 5 查询最新的用户信息
        user = UserService.SelectById(user.getId());
        // 6 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION,user);
        //7 返回结果
        return AppResult.success(user);
    }



    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword")  @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword")  @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat")  @NonNull String passwordRepeat) {

        //1 校验新密码和确认密码是否相同
        if(!newPassword.equals(passwordRepeat)) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2 从session中获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //3 调用service
        UserService.modifyPassword(user.getId(),newPassword,oldPassword);
        //4 销毁session
        if(session != null) {
            session.invalidate();
        }
        //5 返回结果
        return AppResult.success();
    }


    @ApiOperation("用户头像信息")
    @PostMapping("/img")
    public AppResult ModifyPicture(@RequestParam("avatar") MultipartFile avatar, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        log.info("执行开始");
        //判断上传文件是否为空
        if(avatar.isEmpty()) {
            log.error(ResultCode.FAILED.toString() + "文件为空");
            return AppResult.failed(ResultCode.FAILED);
        }
        //获取图片后缀名
        String fileName = avatar.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //后缀格式错误
        if (!suffix.equals(".png") && !suffix.equals(".jpg") && !suffix.equals(".jpeg")) {
            log.debug(AppResult.failed(ResultCode.FAILED).toString() + "图片格式错误");
            return AppResult.failed("图片格式错误");
        }
        //使用UUID生成随机文件名
        String nameFile = UUIDUtil.UUID_32();
        nameFile += suffix;
        //图片的保存路径
        String savePath = "E:/Code/Java_code/forum/forum/src/main/resources/static/img/";
        //String savePath = "/root/forum/img";
        File files = new File(savePath,nameFile);
        if(!files.exists()) {
            files.getParentFile().mkdirs();
        }
        //System.out.println(files.getAbsolutePath());   //绝对路径
        try {
            avatar.transferTo(files);
            log.info("头像上传到指定位置" + files.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String src = "/img/" + nameFile;
        UserService.img(user.getId(),src);
        log.info("头像相对路径写入数据库" + src);
        /**
         * 由于用户头像发生变化,所以更新Redis中的信息
         */
        List<Article> articles = articleService.selectAll();
        redisListUtil.overwriteListInRedis(AppConfig.ARTICLE_KEY,articles);
        log.info("头像地址返回前端");
        return AppResult.success(src);
    }

}
